/**
 * Created by reeves on 2017/1/25.
 */
import {Meteor} from 'meteor/meteor';

Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    waitOn: function () {
        return [Meteor.subscribe('notifications'), Meteor.subscribe('category'), Meteor.subscribe('userStars', (Meteor.userId() == null) ? '' : Meteor.userId())];
    }
});

// 提交帖子路由
Router.route('/submit', {
    name: 'postSubmit'
});

// 根据关键词搜索帖子
// 这个路由要放到其他posts前面，否则无法匹配到
Router.route('/posts/search', {
    name: 'postSearch',
    waitOn: function () {
        return Meteor.subscribe('search', this.params.query.keywords, {sort: {star: -1, submitted: -1}});
    },
    data: function () {
        return {
            posts: Posts.find({}, {sort: {star: -1, submitted: -1}}),
            category: Category.find()
        };
    }
});

// 我的收藏
Router.route('/my/starPosts/:colorFilter', {
    name: 'starPosts',
    template: 'starPosts',
    waitOn: function () {
        var postsIds = [];
        if (this.params.colorFilter == 'all') {
            var starRecords = Star.find({userId: Meteor.userId()}, {sort: {time: 1}});
            starRecords.forEach(function (record) {
                postsIds.push(record.postId);
            });
        } else {
            var starRecords = Star.find({
                userId: Meteor.userId(),
                markColorClass: this.params.colorFilter
            }, {sort: {time: 1}});
            starRecords.forEach(function (record) {
                postsIds.push(record.postId);
            });
        }

        Meteor.subscribe('starPosts', {in: postsIds});
    }
});

// 查看单个帖子
Router.route('/posts/:_id', {
    name: 'postPage',
    waitOn: function () {
        return [
            Meteor.subscribe('singlePost', this.params._id),
            Meteor.subscribe('comments', this.params._id)
        ];
    },
    data: function () {
        return Posts.findOne(this.params._id);
    }
});

//分类文章汇总 - 按时间排序
Router.route('/category/new/:name', {
    name: 'postCategoryNew',
    template: 'postCategoryNew',
    waitOn: function () {
        return Meteor.subscribe('categoryPost', this.params.name);
    },
    data: function () {
        return {
            posts: Posts.find({}, {sort: {submitted: -1}}),
            category: Category.find(),
            currentCategory: this.params.name
        }
    }
});

//分类文章汇总 - 按热度排序
Router.route('/category/:name', {
    name: 'postCategory',
    waitOn: function () {
        return Meteor.subscribe('categoryPost', this.params.name);
    },
    data: function () {
        return {
            posts: Posts.find({}, {sort: {star: -1, submitted: -1}}),
            category: Category.find(),
            currentCategory: this.params.name
        }
    }
});

//编辑帖子路由
Router.route('/posts/:_id/edit', {
    name: 'postEdit',
    waitOn: function () {
        return Meteor.subscribe('singlePost', this.params._id);
    },
    data: function () {
        return {
            post: Posts.findOne(this.params._id),
            category: Category.find()
        }
    }
});

//用户反馈
Router.route('/feedback', {
    name: 'feedback',
    waitOn: function () {
        return Meteor.subscribe('feedback');
    }
    ,
    data: function () {
        return {
            category: Category.find(),
            feedback: Feedback.find({}, {sort: {time: -1}})
        }
    }
});

//关于
Router.route('/about', {
    name: 'about',
    data: function () {
        return {
            category: Category.find()
        }
    }
});

// 首页路由
PostsListController = RouteController.extend({
    template: 'postsList',
    increment: 30,
    postsLimit: function () {
        return parseInt(this.params.postsLimit) || this.increment;
    },
    findOptions: function () {
        return {sort: {star: -1}, limit: this.postsLimit()};
    },
    subscriptions: function () {
        this.postsSub = Meteor.subscribe('posts', this.findOptions());
    },
    posts: function () {
        return Posts.find({}, this.findOptions());
    },
    category: function () {
        return Category.find();
    },
    data: function () {
        var hasMore = this.posts().count() === this.postsLimit();
        var nextPath = this.route.path({postsLimit: this.postsLimit() + this.increment});
        return {
            posts: this.posts(),
            category: this.category(),
            ready: this.postsSub.ready,
            nextPath: hasMore ? nextPath : null
        };
    }
});

// 首页路由
Router.route('/:postsLimit?', {
    name: 'postsList'
});

// 首页按热度排序
Router.route('/new/:limit?', {
    name: 'newPostsList',
    template: 'postsNewList',
    waitOn: function () {
        Meteor.subscribe('posts', {
            sort: {submitted: -1},
            limit: (parseInt(this.params.limit) || 30)
        });
    },
    data: function () {
        var hasMore = Posts.find().count() === (parseInt(this.params.limit) || 30);
        var nextPath = '/new/' + ((parseInt(this.params.limit) || 30) + 30);

        return {
            ready: true,
            nextPath: hasMore ? nextPath : null
        }
    }
});


var requireLogin = function () {
    if (!Meteor.user()) {
        if (Meteor.loggingIn()) {
            this.render(this.loadingTemplate);
        } else {
            this.render('accessDenied');
        }
    } else {
        this.next();
    }
}

Router.onBeforeAction('dataNotFound', {only: 'postPage'});
Router.onBeforeAction(requireLogin, {only: 'postSubmit'});